package com.woniuxy.user.config;


import com.woniuxy.user.entity.User;
import com.woniuxy.user.service.CustomUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class TokenConfiguration {
    // 密码
    private static String SIGNING_KEY="www.woniuxy.com";
    @Resource
    private CustomUserDetailsService customUserDetailsService;
    @Resource
    private DataSource dataSource;

    // token转换器
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter =
                new JwtAccessTokenConverter(){
                    @Override
                    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                        final Map<String,Object> map = new HashMap<>();
                        // 获取用户名
                        String username = authentication.getName();

                        // 通过账号查询用户信息
                        User user = (User) customUserDetailsService.loadUserByUsername(username);

                        // 将用户id放到token中
                        map.put("uid", user.getId());
                        ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(map);
                        // 返回
                        return super.enhance(accessToken, authentication);
                    }
                };
        jwtAccessTokenConverter.setSigningKey(SIGNING_KEY);
        return jwtAccessTokenConverter;
    }


    // 令牌存储策略:jwt方式
    @Bean
    public TokenStore tokenStore(){
        return new JdbcTokenStore(dataSource);
    }
}
